#include "gd32w51x.h"
#include "stdint.h"
#include "stdio.h"
#include "DevicesPWM.h"

void vPWMOutputInit(void)
{
    timer_oc_parameter_struct timer_ocintpara = {0};
    timer_parameter_struct timer_initpara = {0};


    /* enable the GPIO clock */
    rcu_periph_clock_enable(RCU_GPIOB);

    /* configure GPIO pin */
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLDOWN, GPIO_PIN_0);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, GPIO_PIN_0);
    gpio_af_set(GPIOB, GPIO_AF_3, GPIO_PIN_0);


    rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);
    rcu_periph_clock_enable(RCU_TIMER3);

    timer_channel_output_struct_para_init(&timer_ocintpara);
    timer_struct_para_init(&timer_initpara);
    timer_deinit(TIMER3);

    /* ROLLING_BRUSH_TIMER configuration */
    timer_initpara.prescaler         = 18 - 1;
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period            = (SystemCoreClock / timer_initpara.prescaler / 37000) - 1;
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(TIMER3, &timer_initpara);

    /* CH0,CH1 and CH2 configuration in PWM mode */
    timer_ocintpara.outputstate  = TIMER_CCX_ENABLE;
    timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE;
    timer_ocintpara.ocpolarity   = TIMER_OC_POLARITY_LOW;
    timer_ocintpara.ocnpolarity  = TIMER_OCN_POLARITY_HIGH;
    timer_ocintpara.ocidlestate  = TIMER_OC_IDLE_STATE_HIGH;
    timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;

    timer_channel_output_config(TIMER3, TIMER_CH_0, &timer_ocintpara);

    /* ROLLING_BRUSH_TIMER_CHANNEL configuration in PWM mode1,duty cycle 0% */
    timer_channel_output_pulse_value_config(TIMER3, TIMER_CH_0, timer_initpara.period / 3);
    timer_channel_output_mode_config(TIMER3, TIMER_CH_0, TIMER_OC_MODE_PWM1);
    timer_channel_output_shadow_config(TIMER3, TIMER_CH_0, TIMER_OC_SHADOW_DISABLE);
	timer_channel_output_state_config(TIMER3, TIMER_CH_0, TIMER_CCX_ENABLE);

    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(TIMER3);

    /* auto-reload preload enable */
    timer_enable(TIMER3);
}
